package com.yc.java8.stream;

import com.yc.thread.synch.SyncVSCAS;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * stream 操作
 */
public class StreamDemo {

    public static void main(String[] args) {
        StreamDemo sd = new StreamDemo();
//        try {
//            sd.testOne();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        sd.testStream();
    }

    /**
     * 流的一些基本操作
     */
    public void testStream() {
        // 流的构造
        // 方式1

        Stream<String> a = Stream.of("a", "b", "c");
        a.forEach(System.out :: println);
        // 方式2
        String[] strArr = new String[]{"a", "b", "c"};
        Stream<String> strArr1 = Stream.of(strArr);
        Stream<String> stream = Arrays.stream(strArr);
        strArr1.forEach(e -> System.out.println(e));
        stream.forEach((e) -> {
            System.out.println(e);
        });

        // reduce使用
        String testReduce1 = a.reduce("开始", (x, y) -> x + y);
        System.out.println(testReduce1);
        Stream<Integer> integerStream = Stream.of(2, 4, 3, 7, 1);
        integerStream.reduce(0 , Integer::sum);

        // mapToLog
        LongStream longStream = integerStream.mapToLong(e -> e + 1L);//.collect(Collectors.toList());

        // 首字母转大写
        List<String> collect = Stream.of("hello", "world", "java8", "stream", "test")
                .map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1))
                .collect(Collectors.toList());
        collect.stream().forEach(System.out :: println);

    }


    /**
     * 执行效率的比较
     */
    public void testOne() throws Exception{
        List<Integer> list = new ArrayList<>();
        Random random = new Random();
//        while (i<10000) {
//            int r = random.nextInt(10000);
//            list.add(r);
//            i ++ ;
//        }
        int i = 0;
        do {
            int r = random.nextInt(10000);
            list.add(r);
            i ++;
        } while (i<10000);

        long start1 = System.currentTimeMillis();
        list.stream().forEach((t) -> {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end1 = System.currentTimeMillis();
        System.out.println("==" + (end1 - start1) + "毫秒");


        long start2 = System.currentTimeMillis();
        for(int j=0; j<list.size(); j++) {
//            System.out.println(list.get(j));
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long end2 = System.currentTimeMillis();
        System.out.println("==" + (end2 - start2) + "毫秒");
    }
}
